package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Slf4j
@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisData.setData(value);
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack,Long time, TimeUnit unit){
        String key = keyPrefix+id;
        //从redis查询商品缓存
        String Json = stringRedisTemplate.opsForValue().get(key);

        //如果查到了就直接返回
        if(StrUtil.isNotBlank(Json)){
            return JSONUtil.toBean(Json, type);
        }
        if(Json!=null){
            return null;
        }

        //如果没查到就从数据库里查
        R r = dbFallBack.apply(id);

        //如果数据库不存在就返回错误
        if(r==null){
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        //如果数据库存在就写入redis缓存
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r),time, unit);

        //返回
        return r;
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    /**
     * 通过给热点信息设置逻辑过期时间来解决缓存击穿问题
     * @param id
     * @return
     */
    public <R,ID> R queryWithLogicalExpire(
            String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack,Long time, TimeUnit unit, String lockKeyPrefix
    ){
        String key = keyPrefix+id;
        //从redis查询商品缓存
        String Json = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //如果不存在就直接返回null
        if(StrUtil.isBlank(Json)){
            return null;
        }
        //命中，需要把json反序列化对象
        RedisData redisData = JSONUtil.toBean(Json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        //如果没有过期，直接返回店铺信息
        if(expireTime.isAfter(LocalDateTime.now())){
            return r;
        }
        //过期了就要开始缓存重建
        //首先获取互斥锁
        String lockKey = lockKeyPrefix+id;
        if(tryLock(lockKey)){
            //如果获取成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //重建缓存，先查数据库
                    R r1 = dbFallBack.apply(id);
                    //再写入redis
                    this.setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockKey);
                }
            });
        }
        //如果获取失败，直接返回过期商铺信息
        return r;
    }

    //获取自定义锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10L, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放自定义锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
